package com.hanxu.springboot04web.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Map;

/**
 * 数据处理
 */
@RestController
public class JdbcController {


    /**
     * 操作数据库的模板
     */
    @Autowired
    JdbcTemplate jdbcTemplate;


    /**
     * 获取所有的用户
     * @return
     */
    @GetMapping("/userlist")
    public List<Map<String,Object>> userList(){
        String sql = "select * from student";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;

    }

    /**
     * 添加用户
     * 会自动提交事务
     * @return
     */
    @GetMapping("/adduser")
    public String addUser(){
        String sql = "insert into student (id,name,tid) values (6,'小于',1)";
        int update = jdbcTemplate.update(sql);
        return "addUser-ok";
    }

    /**
     * restfor风格
     * 修改用户
     * 会自动提交事务
     * @return
     */
    @GetMapping("/updateuser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update student set name = ? where id ="+id;

        Object[] objects = new Object[1];
        objects[0] = "战士";

        int update = jdbcTemplate.update(sql,objects);
        return "updateUser-ok";
    }

    /**
     * 删除用户
     * 会自动提交事务
     * @return
     */
    @GetMapping("/deleteuser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from student where id = ?";
        int update = jdbcTemplate.update(sql,id);
        return "deleteuser-ok";
    }


}
